package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.View;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.imgedit.utils.Matrix3;
import com.stark.imgedit.view.imagezoom.ImageViewTouchBase;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.ColorAdapter;
import flc.ast.bean.IdPhotosBean;
import flc.ast.bean.MyColorBean;
import flc.ast.databinding.ActivityCutPhotoBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.apis.ApiManager;
import stark.common.base.IReqRetCallback;
import stark.common.basic.utils.DensityUtil;
import stark.common.basic.utils.RxUtil;

public class CutPhotoActivity extends BaseAc<ActivityCutPhotoBinding> {

    public static Bitmap sBitmap;
    private ColorAdapter colorAdapter;
    private int oldPosition;
    private boolean isClip = false;
    private Bitmap saveBitmap;

    @Override
    protected int onCreate() {
        return R.layout.activity_cut_photo;
    }

    @Override
    protected void initView() {
        mDataBinding.ivCutPhotoBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.tvBgColor.setOnClickListener(this);
        mDataBinding.tvPhotoCut.setOnClickListener(this);
        mDataBinding.ivPreviewNext.setOnClickListener(this);

        mDataBinding.rvBgColorList.setLayoutManager(new GridLayoutManager(mContext, 5));
        colorAdapter = new ColorAdapter();
        mDataBinding.rvBgColorList.setAdapter(colorAdapter);
        colorAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.tvBgColor://背景颜色
                clearSelection();
                mDataBinding.tvBgColor.setTextColor(Color.parseColor("#5AD9FF"));
                mDataBinding.rvBgColorList.setVisibility(View.VISIBLE);
                break;
            case R.id.tvPhotoCut://图片裁剪
                clearSelection();
                isClip = true;
                mDataBinding.tvPhotoCut.setTextColor(Color.parseColor("#5AD9FF"));
                mDataBinding.llSpecification.setVisibility(View.VISIBLE);
                mDataBinding.cropImgView.setVisibility(View.VISIBLE);
                break;
            case R.id.ivPreviewNext://下一步
                clipsImg();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        colorAdapter.getItem(oldPosition).setSelect(false);
        oldPosition = position;
        colorAdapter.getItem(position).setSelect(true);
        colorAdapter.notifyDataSetChanged();
        mDataBinding.rlSave.setBackgroundColor(Color.parseColor(colorAdapter.getItem(position).getColor()));
    }

    @Override
    protected void initData() {
        IdPhotosBean bean = Content.sIdPhotosBean;
        mDataBinding.tvSpecification.setText(getString(R.string.specification_detail, bean.getPixelW() + "x" + bean.getPixelH(), bean.getCyW() + "x" + bean.getCyH()));
        mDataBinding.tvPixelW.setText(bean.getPixelW() + getString(R.string.px_text) + " / " + bean.getCyW() + getString(R.string.mm_text));
        mDataBinding.tvPixelH.setText(bean.getPixelH() + getString(R.string.px_text) + " / " + bean.getCyH() + getString(R.string.mm_text));
        //人像识别
        identify();
        //背景颜色
        List<MyColorBean> listColor = new ArrayList<>();
        listColor.add(new MyColorBean("#428EDB", true));
        listColor.add(new MyColorBean("#02BFF3", false));
        listColor.add(new MyColorBean("#FFFFFF", false));
        listColor.add(new MyColorBean("#FF0000", false));
        listColor.add(new MyColorBean("#D9001B", false));
        colorAdapter.setList(listColor);
        mDataBinding.rlSave.setBackgroundColor(Color.parseColor(listColor.get(0).getColor()));
    }

    private void identify() {
        showDialog(getString(R.string.loading));
        ApiManager.humanApi().hmBodySegBmp(this, sBitmap, new IReqRetCallback<Bitmap>() {
            @Override
            public void onResult(boolean success, String msg, @Nullable Bitmap result) {
                if (result != null) {
                    RxUtil.create(new RxUtil.Callback<Bitmap>() {
                        @Override
                        public void doBackground(ObservableEmitter<Bitmap> emitter) {
                            int width = DensityUtil.getWith(mContext) / 2;
                            int height = DensityUtil.getHeight(mContext) / 2;
                            Bitmap bitmap = null;
                            try {
                                bitmap = Glide.with(mContext).asBitmap().load(result)
                                        .submit(width, height).get();
                                emitter.onNext(bitmap);
                            } catch (ExecutionException | InterruptedException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void accept(Bitmap bitmap) {
                            if (bitmap != null) {
                                mDataBinding.imageViewTouch.setImageBitmap(bitmap);
                                mDataBinding.imageViewTouch.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);
                                mDataBinding.imageViewTouch.setScaleEnabled(false);// 禁用缩放
                                mDataBinding.imageViewTouch.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        RectF bitmapRect = mDataBinding.imageViewTouch.getBitmapRect();
                                        mDataBinding.cropImgView.setCropRect(bitmapRect);
                                    }
                                });
                                dismissDialog();
                            }
                        }
                    });
                } else {
                    dismissDialog();
                    ToastUtils.showShort(getString(R.string.identify_error));
                    finish();
                }
            }
        });
    }

    //裁剪图片
    private void clipsImg() {
        showDialog(getString(R.string.loading));
        RxUtil.create(new RxUtil.Callback<Bitmap>() {
            @Override
            public void doBackground(ObservableEmitter<Bitmap> emitter) {
                RectF cropRect = mDataBinding.cropImgView.getCropRect();// 剪切区域矩形
                Matrix touchMatrix = mDataBinding.rlSave.getMatrix();
                float[] data = new float[9];
                touchMatrix.getValues(data);// 底部图片变化记录矩阵原始数据
                Matrix3 cal = new Matrix3(data);// 辅助矩阵计算类
                Matrix3 inverseMatrix = cal.inverseMatrix();// 计算逆矩阵
                Matrix m = new Matrix();
                m.setValues(inverseMatrix.getValues());
                m.mapRect(cropRect);// 变化剪切矩形

                mDataBinding.cropImgView.setVisibility(View.INVISIBLE);
                Bitmap bitmap = ImageUtils.view2Bitmap(mDataBinding.rlSave);

                Bitmap resultBit = Bitmap.createBitmap(bitmap,
                        (int) cropRect.left, (int) cropRect.top,
                        (int) cropRect.width(), (int) cropRect.height());
                emitter.onNext(resultBit);
            }

            @Override
            public void accept(Bitmap bitmap) {
                dismissDialog();
                if (isClip) {
                    saveBitmap = bitmap;
                } else {
                    saveBitmap = ImageUtils.view2Bitmap(mDataBinding.rlSave);
                }
                ProfessionalPhotoActivity.sBitmap = saveBitmap;
                ProfessionalPhotoActivity.type = 0;
                startActivity(ProfessionalPhotoActivity.class);
                mDataBinding.cropImgView.setVisibility(View.VISIBLE);
            }
        });
    }

    private void clearSelection() {
        mDataBinding.tvBgColor.setTextColor(Color.parseColor("#868484"));
        mDataBinding.tvPhotoCut.setTextColor(Color.parseColor("#868484"));
        mDataBinding.rvBgColorList.setVisibility(View.GONE);
        mDataBinding.llSpecification.setVisibility(View.GONE);
        mDataBinding.cropImgView.setVisibility(View.GONE);
    }

}